import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Task } from '../../pages/tasklist/task';



@Injectable()
export class HttpDataProvider {

  private readonly baseUrl: string ='https://api2.bmob.cn/1';
  private readonly httpOptions : Object = {
    headers : new HttpHeaders({
      'X-Bmob-Application-Id': 'ed4c6c9da67c6be4f4540b03c7051471',
      'X-Bmob-REST-API-Key': '32a2f2d7c71151bb0f4883919aa1b115',
      'Content-Type': 'application/json',
    })
  };

  constructor(public http: HttpClient) {
    console.log('获取HTTP数据服务加载');
  }

  /**
   * 获取待办事项列表
   * @returns{Observable<Task[]>} 待办事项列表数据集合
   */
   getTaskList(): Observable<Task[]>{
    return this.http.get<Task[]>(`${this.baseUrl}/classes/ToDoList`, 
    this.httpOptions).map(data => data["results"]);
    
   }

   
   /**
    * 
    * @param task 新增待办事项
    *  @returns{Observable<Task[]>} 响应结果
    */
   addTask(task: Task): Observable<Task>{
    let _task = {title: task.title, status: task.status, description:
    task.description};
    return this.http.post<Task>(`${this.baseUrl}/classes/ToDoList/`, _task,
    this.httpOptions);
   }

   /**
    * 更新指定待办事项
    * @param task 
    * @returns{Observable<Task[]>} 响应结果
    */
   updateTask(task : Task): Observable<Task>{
     let _task = {title: task.title, status: task.status, description:
     task.description};
     return this.http.put<Task>(`${this.baseUrl}/classes/ToDoList/${task.objectId}`, _task,
     this.httpOptions);
   }

   deleteTask(task : Task): Observable<{}>{
     return this.http.delete(`${this.baseUrl}/classes/ToDoList/${task.objectId}`,
     this.httpOptions);
   }
}
